define('addCollage',
    ['jquery', 'styleloader', 'fabric', 'getCanvas'],
    function ($, styleloader, fabric, getCanvas) {

        var canvas = null, photoRecord = {}, photoRecords = [], currentPhotoId = 0;

        function setupCollage(url, obj, btn) {

		var photoid = parseInt($(btn).attr('id').slice(14));
		currentPhotoId = photoid-1;
		
		if(typeof photoRecords[currentPhotoId] == 'undefined')
		{
			photoRecord = {
				_obj: obj,
				_btn: btn,
				_added: false,
				_img: null
			}
			photoRecords[currentPhotoId] = photoRecord;
		}

              getCanvas.setupCanvas(function(can) {
                 canvas = can;
				 addPhoto(url, obj, btn);
				 
              });
		}
		
		function addPhoto(photosrc, ph, btn) {
						fabric.Image.fromURL(photosrc, function(img) {
							img.set({ 
								left: ph.left, 
								top: ph.top, 
								angle: 0, 
								transparentCorners: true,
								borderColor: '#6058fd',
								cornerColor: '#0a029a',
								cornerSize: 15,
								rotatingPointOffset: -20,
								clipTo: function(ctx) {
									roundRect(ctx, -img.width/2, -img.height/2, img.width, img.height, 0, "", "");
								}
							}).setWidth(ph.width).setHeight(ph.height);
							img.perPixelTargetFind = true;
							img.targetFindTolerance = 4;
							img.hasControls = img.hasBorders = img.selectable = true;
							img.lockMovementX = img.lockMovementY = img.lockScalingX = img.lockScalingY = img.lockRotation = true;
							img.id = $(btn).attr('id');
							$('#side-ui').animate({opacity: 0.9, height:300, width:250 },100).hide();

							if(photoRecords[currentPhotoId]._added)
							{
								canvas.remove(photoRecords[currentPhotoId]._img);
								photoRecords[currentPhotoId]._img = img;
								canvas.add(img);
							} else
							{
								canvas.add(img);
								photoRecords[currentPhotoId]._img = img;
								photoRecords[currentPhotoId]._added = true;
							}
							canvas.sendToBack(img);
							canvas.bringForward(img);
							$(btn).hide();
							
						});
		}
	
					function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
						  if (typeof stroke == "undefined" ) {
							stroke = true;
						  }
						  if (typeof radius === "undefined") {
							radius = 5;
						  }
						  ctx.beginPath();
						  ctx.moveTo(x + radius, y);
						  ctx.lineTo(x + width - radius, y);
						  ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
						  ctx.lineTo(x + width, y + height - radius);
						  ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
						  ctx.lineTo(x + radius, y + height);
						  ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
						  ctx.lineTo(x, y + radius);
						  ctx.quadraticCurveTo(x, y, x + radius, y);
						  ctx.closePath();
						  if (stroke) {
							ctx.stroke();
						  }
					}

        return {
            setupCollage: setupCollage
        };

    }
);